<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="计费模型名称" prop="billingModelName">
        <el-input
          v-model="queryParams.billingModelName"
          placeholder="请输入计费模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['quoteModel:quoteModel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['quoteModel:quoteModel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['quoteModel:quoteModel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['quoteModel:quoteModel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="quoteModelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="计费模型名称" align="center" prop="billingModelName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['quoteModel:quoteModel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['quoteModel:quoteModel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改引用计费模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <div style="display: flex;flex-direction: row;justify-content: space-between">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="计费模型名称" prop="billingModelName">
            <el-input v-model="form.billingModelName" placeholder="请输入计费模型名称" style="width: 200px"/>
          </el-form-item>
        </el-form>
        <el-button size="small" style="height: 36px" type="success" @click="addDomain">新增区间</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="modelDataList"
        @selection-change="handleSelectionChange">

        <el-table-column
          label="顺序号"
          align="center"
          prop="sortNum"/>
        <el-table-column
          label="起始时间"
          align="center"
          prop="beginDuration">
          <template slot-scope="scope">
            <el-time-select
              :clearable="false"
              :editable="false"
              :disabled="scope.$index===0"
              v-model="scope.row.startTime"
              :picker-options="scope.row.pickerOptions"
              @change="timeChange($event,scope.$index)"
              placeholder="选择时间">
            </el-time-select>
          </template>
        </el-table-column>
        <el-table-column
          label="服务费"
          align="center"
          prop="servicePrice">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.servicePrice"
              placeholder="请输入服务费"
              oninput="value=value.replace(/[^\d.]/g,'')"/>
          </template>
        </el-table-column>
        <el-table-column
          label="电价"
          align="center"
          prop="electricityPrice">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.electricityPrice"
              placeholder="请输入电价"
              oninput="value=value.replace(/[^\d.]/g,'')"/>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="electricityPrice">
          <template slot-scope="scope">
            <el-button v-if="scope.$index>0" @click="handleDomain(scope.$index)" type="primary" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuoteModel, getQuoteModel, delQuoteModel, addQuoteModel, updateQuoteModel } from "@/api/business/quoteModel";
import { ChangeHourMinutestr, ChangeStrToMinutes } from '@/utils/common'
import {addModel, updateModel} from "@/api/business/model";

const modelDataList = [{ sortNum: 1, beginDuration: 0, startTime: '00:00', pickerOptions: { start: '00:00', step: '00:30', end: '23:30' }, servicePrice: 0, electricityPrice: 0 }]
const modelDataList2 = [
  { sortNum: 1, beginDuration: 0, min: 0, servicePrice: 0, electricityPrice: 0 },
  { sortNum: 2, beginDuration: 250, min: 50, servicePrice: 0, electricityPrice: 0 },
  { sortNum: 3, beginDuration: 500, min: 100, servicePrice: 0, electricityPrice: 0 },
  { sortNum: 4, beginDuration: 750, min: 150, servicePrice: 0, electricityPrice: 0 },
  { sortNum: 5, beginDuration: 1000, min: 200, servicePrice: 0, electricityPrice: 0 },
  { sortNum: 6, beginDuration: 1250, min: 250, servicePrice: 0, electricityPrice: 0 }]
export default {
  name: "QuoteModel",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 引用计费模型表格数据
      quoteModelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billingModelName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billingModelName: [
          { required: true, message: '计费模型名称不能为空', trigger: 'blur' }
        ]
      },
      resultObj: null,
      deviceTypeList: [],
      modelDataList: [],
      modelDataList2: [],
      protocolTypeList: [],
      stageTypeList: [],
    };
  },
  created() {
    this.getList();
  },
  filters: {
    getH (val) {
      return ChangeHourMinutestr(val)
    },
    getPrice(val) {
      return (val/100).toFixed(2)
    }
  },
  methods: {
    /** 查询引用计费模型列表 */
    getList() {
      this.loading = true;
      listQuoteModel(this.queryParams).then(response => {
        this.quoteModelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        billingModelName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const modelDataList = [{ sortNum: 1, beginDuration: 0, startTime: '00:00', pickerOptions: { start: '00:00', step: '00:30', end: '23:30' }, servicePrice: 0, electricityPrice: 0 }]
      this.reset()
      this.modelDataList = modelDataList
      this.modelDataList2 = modelDataList2
      this.open = true;
      this.title = "添加引用计费模型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.modelDataList2 = modelDataList2
      const id = row.id || this.ids
      getQuoteModel(id).then(response => {
        this.form = response.data.quoteBillingModel
        this.handleBillModel(response.data.quoteBillingModelStages)
        this.open = true;
        this.title = "修改引用计费模型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.bthLoading=true
          let copyList = JSON.parse(JSON.stringify(this.modelDataList))
          copyList.forEach(item => {
            item.servicePrice = Math.round((item.servicePrice * 100))
            item.electricityPrice = Math.round((item.electricityPrice * 100))
          })
          this.form.billingModelStageList = copyList
          if (this.form.id != null) {
            updateQuoteModel(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.bthLoading=false
              this.open = false
              this.getList()
            })
          } else {
            addQuoteModel(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.bthLoading=false
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除引用计费模型编号为"' + ids + '"的数据项？').then(function() {
        return delQuoteModel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('quoteModel/quoteModel/export', {
        ...this.queryParams
      }, `quoteModel_${new Date().getTime()}.xlsx`)
    },
    addDomain(){
      if (this.modelDataList.length>=8) {
        this.$message.error("不能添加超过8条");
        return
      }
      if (this.modelDataList[this.modelDataList.length-1].beginDuration >=1410) {
        this.$message.error("最后一组数据为'23:30'不能添加新的时间区间");
        return
      }
      //设置新数据
      let mode = JSON.parse(JSON.stringify(this.modelDataList[this.modelDataList.length-1]));
      mode.sortNum = this.modelDataList.length+1
      mode.beginDuration =  this.modelDataList[this.modelDataList.length-1].beginDuration + 30
      mode.startTime = ChangeHourMinutestr(mode.beginDuration)

      //修改旧数据
      this.modelDataList[this.modelDataList.length-1].pickerOptions.end = ChangeHourMinutestr(mode.beginDuration - 30)
      this.modelDataList.push(mode)
    },
    handleChangePower(e, index) {
      this.recurrence2(e, index)
    },
    recurrence2 (e, index) {
      if (index >= this.modelDataList2.length - 1) return
      if (this.modelDataList2[index].beginDuration >= this.modelDataList2[index + 1].beginDuration) {
        this.modelDataList2[index + 1].beginDuration = this.modelDataList2[index + 1].beginDuration + 50
        return this.recurrence2((this.modelDataList2[index + 1].beginDuration), index + 1)
      }
      if (this.modelDataList2[index].beginDuration <= this.modelDataList2[index - 1].beginDuration) {
        this.modelDataList2[index - 1].beginDuration = this.modelDataList2[index - 1].beginDuration - 50
        return this.recurrence2((this.modelDataList2[index - 1].beginDuration), index - 1)
      }
    },
    handleBillModel (list) {
      list.forEach((item,index)=>{
        //Object.assign(this.modelDataList[index],item)
        item.startTime = ChangeHourMinutestr(item.beginDuration)
        item.electricityPrice = item.electricityPrice / 100
        item.servicePrice = item.servicePrice / 100
        let itemIndex = 0
        if (index > 0) itemIndex = index - 1
        item.pickerOptions = { start: list[itemIndex].startTime, step: '00:30', end: '23:30' }
      })
      this.modelDataList = list
      this.modelDataList2.forEach((item,index)=>{
        Object.assign(item,list[index])
        //item.electricityPrice = item.electricityPrice
        //item.servicePrice = item.servicePrice
      })
    },
    /** 时间替换 **/
    timeChange (e, index) {
      this.modelDataList[index].beginDuration = ChangeStrToMinutes(e)
      this.recurrence(e, index)
    },
    recurrence (e, index) {
      if (index >= this.modelDataList.length - 1) return
      this.modelDataList[index + 1].pickerOptions.start = ChangeHourMinutestr(this.modelDataList[index].beginDuration + 30)
      if (this.modelDataList[index].beginDuration >= this.modelDataList[index + 1].beginDuration) {
        this.modelDataList[index + 1].beginDuration = this.modelDataList[index].beginDuration + 30
        this.modelDataList[index + 1].startTime = ChangeHourMinutestr(this.modelDataList[index + 1].beginDuration)
        return this.recurrence(ChangeHourMinutestr(this.modelDataList[index + 1].beginDuration), index + 1)
      }
    },
    handleDomain(index){
      this.modelDataList.splice(index, 1)
      this.modelDataList.forEach((item,num)=>{
        item.sortNum = num+1
      })
    },
  }
};
</script>
